import { RouteRecordRaw } from 'vue-router'
import allAsyncRoutes from '@/router/async-routes'
import { deepClone } from './common'

/**
 * 从菜单中筛选导航菜单
 * @param userMenus 完整用户菜单
 */
export function menusToNavMenus(userMenus: any[]): any[] {
  const navMenus = _filterNavMenus(userMenus)

  function _filterNavMenus(data: any[]) {
    const temp = deepClone(data)
    const tree = temp.filter((item: any) => {
      if (item.children && item.children.length) {
        item.children = _filterNavMenus(item.children)
      }
      return item.type === 0
    })

    return tree
  }

  return navMenus
}

/**
 * 从菜单中筛选权限节点
 * @param userMenus 完整用户菜单
 */
export function menusToPermissions(userMenus: any[]): any[] {
  const permissions: string[] = []

  _filterPermissions(userMenus)

  function _filterPermissions(data: any[]) {
    for (const item of data) {
      if (item.type === 1) {
        permissions.push(item.permission)
      }

      if (item.children && item.children.length) {
        _filterPermissions(item.children)
      }
    }
  }

  return permissions
}

/**
 * 从菜单中筛选动态路由
 * @param navMenus 导航菜单
 */
export function menusToRoutes(navMenus: any[]): RouteRecordRaw[] {
  const asyncRoutes: RouteRecordRaw[] = []

  _filterRoutes(navMenus)

  function _filterRoutes(data: any[]) {
    for (const item of data) {
      if (item.children && item.children.length) {
        _filterRoutes(item.children)
        continue
      }
      const foundRoute = allAsyncRoutes.find((route) => route.path === item.url)
      if (foundRoute) {
        asyncRoutes.push(foundRoute)
      }
    }
  }

  return asyncRoutes
}

/**
 * 从菜单中筛选面包屑数据
 * @param navMenus 导航菜单
 * @param currentRoutePath 当前路由路径
 */
export function menusToBreadcrembs(navMenus: any[], currentRoutePath: string): any[] {
  const breadcrumbs: any[] = []

  _filterBreadcrembs(navMenus)

  function _filterBreadcrembs(data: any[]): boolean {
    const menu = data.find((item) => {
      if (item.children && item.children.length) {
        return _filterBreadcrembs(item.children)
      }

      return item.url === currentRoutePath
    })

    if (menu) {
      breadcrumbs.push({ name: menu.name, path: menu.url })
    }

    return menu !== undefined
  }

  return breadcrumbs.reverse()
}
